import styled from "@emotion/styled";
import { Form, Input, Button, Row, Col, message } from "antd";
import { DingdingOutlined, MobileOutlined } from '@ant-design/icons';
import { useState } from "react";
import useLoginModel from "../../model/useLoginModel";
import { useInterval } from "ahooks";

const ValidcodeLogin: React.FC = () => {
    const user = useLoginModel()

    const [mobile, setMobile] = useState<string>()
    const [count, setCount] = useState(60);
    const [interval, setInterval] = useState<number | null>(null);

    useInterval(
        () => {
            if (count === 0) {
                setCount(60)
                setInterval(null)
            } else {
                setCount(count - 1);
            }
        },
        interval,
        { immediate: false },
    );

    const onFinish = (values: any) => {
        user.mobileLogin(values)
    };

    const sendValidCode = () => {
        if (!mobile) {
            message.warning('请输入手机号!')
            return
        }
        user.send({ mobile: mobile })
        setInterval(1000)
    }

    return <Form
        name="validcode_login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={onFinish}
    >
        <Form.Item
            name="mobile"
            rules={[{ required: true, message: '请输入手机号!' }]}
        >
            <Input onBlur={(data) => { setMobile(data.target.defaultValue) }} prefix={<MobileOutlined className="site-form-item-icon" />} placeholder="手机号" />
        </Form.Item>
        <Form.Item
            name="code"
            rules={[{ required: true, message: '请输入验证码!' }]}
        >
            <Row>
                <Col span={16}>
                    <Input
                        prefix={<DingdingOutlined className="site-form-item-icon" />}
                        placeholder="验证码"
                    />
                </Col>
                <GetCodeCol span={8}>
                    <CodeButton loading={count < 60} onClick={sendValidCode}>
                        {count === 60 ? '获取验证码' : `${count}s后重试`}
                    </CodeButton>
                </GetCodeCol>
            </Row>

        </Form.Item>
        <Form.Item>
            <LoginButton type="primary" htmlType="submit">
                登录
            </LoginButton>
        </Form.Item>
    </Form>
}

const LoginButton = styled(Button)`
    width: 100%;
`

const GetCodeCol = styled(Col)`
    text-align: right;
`

const CodeButton = styled(Button)`
    width: 115px;
`

export default ValidcodeLogin